import React, { useState, useEffect } from 'react'
import { 
  Table, 
  Input, 
  Select, 
  Button, 
  Space, 
  Card, 
  message,
  Popconfirm,
  Upload,
  Dropdown,
  Menu,
  Modal
} from 'antd'
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons'
import { Resizable } from 'react-resizable'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import * as XLSX from 'xlsx'

import 'antd/dist/reset.css'
import 'react-resizable/css/styles.css'

// 类型映射函数
const getTypeValue = (typeStr) => {
  if (typeStr === "输入线电器") return 1
  if (typeStr === "输出线电器") return 2
  if (typeStr === "输入寄存器") return 3
  if (typeStr === "输出寄存器") return 4
  return 0 // 默认值
}

const getTypeString = (typeValue) => {
  switch (typeValue) {
    case 1: return "输入线电器"
    case 2: return "输出线电器"
    case 3: return "输入寄存器"
    case 4: return "输出寄存器"
    default: return ""
  }
}

// 数据类型映射函数
const getDataTypeValue = (dataTypeStr) => {
  if (dataTypeStr === "16位无符号") return 1
  if (dataTypeStr === "16位有符号") return 2
  if (dataTypeStr === "32位无符号") return 3
  if (dataTypeStr === "32位有符号") return 4
  if (dataTypeStr === "32位浮点型") return 5
  if (dataTypeStr === "16位4位BCD") return 6
  if (dataTypeStr === "32位8位BCD") return 7
  return 0 // 默认值
}

const getDataTypeString = (dataTypeValue) => {
  switch (dataTypeValue) {
    case 1: return "16位无符号"
    case 2: return "16位有符号"
    case 3: return "32位无符号"
    case 4: return "32位有符号"
    case 5: return "32位浮点型"
    case 6: return "16位4位BCD"
    case 7: return "32位8位BCD"
    default: return ""
  }
}



// 可调整大小的表头组件
const ResizableTitle = (props) => {
  const { onResize, width, ...restProps } = props

  if (!width) {
    return <th {...restProps} />
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={(
        <span
          className="react-resizable-handle"
          onClick={(e) => {
            e.stopPropagation()
          }}
        />
      )}
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  )
}

// 可编辑表格组件
const EditableTable = ({ fileId, onDataChange }) => {
  const [dataSource, setDataSource] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [currentFileId, setCurrentFileId] = useState(fileId)
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  const [conflictRows, setConflictRows] = useState(new Set()) // 存储有地址冲突的行key
  const [searchKeyword, setSearchKeyword] = useState('') // 搜索关键词
  const [columns, setColumns] = useState([]) // 列配置状态
  const [contextMenuVisible, setContextMenuVisible] = useState(false)
  const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 })
  const [contextMenuRowIndex, setContextMenuRowIndex] = useState(-1)
  // 框选相关状态
  const [isSelecting, setIsSelecting] = useState(false)
  const [selectionStart, setSelectionStart] = useState({ x: 0, y: 0 })
  const [selectionEnd, setSelectionEnd] = useState({ x: 0, y: 0 })
  const [selectionBox, setSelectionBox] = useState({ display: 'none', left: 0, top: 0, width: 0, height: 0 })
  // 撤销重做系统
  const [history, setHistory] = useState([])
  const [historyIndex, setHistoryIndex] = useState(-1)
  const [isUndoRedoOperation, setIsUndoRedoOperation] = useState(false)

  // 初始化列配置
  useEffect(() => {
    const initialColumns = [
      {
        title: '序号',
        dataIndex: 'sequence',
        key: 'sequence',
        width: 80,
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        width: 200,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 120,
      },
      {
        title: '开始地址',
        dataIndex: 'startAddr',
        key: 'startAddr',
        width: 120,
      },
      {
        title: '数据类型',
        dataIndex: 'dataType',
        key: 'dataType',
        width: 120,
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        width: 100,
      },
      {
        title: '值类型',
        dataIndex: 'valueType',
        key: 'valueType',
        width: 150,
      },
      {
        title: '绑定变量',
        dataIndex: 'variable',
        key: 'variable',
        width: 120,
      },
    ]
    setColumns(initialColumns)
  }, [])

  // 从数据库加载数据
  useEffect(() => {
    if (fileId) {
      setCurrentFileId(fileId)
      loadFileData(fileId)
    } else {
      loadDataFromDatabase()
    }
  }, [fileId])

  // 初始化历史记录
  useEffect(() => {
    if (dataSource.length > 0 && history.length === 0) {
      const initialHistoryItem = {
        data: JSON.parse(JSON.stringify(dataSource)),
        selectedRowKeys: [],
        operation: '初始状态',
        timestamp: Date.now()
      }
      setHistory([initialHistoryItem])
      setHistoryIndex(-1)
    }
  }, [dataSource, history.length])

  // 添加键盘事件监听器
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.ctrlKey && event.key === 's') {
        event.preventDefault()
        handleSave()
      }
      
      // 撤销重做快捷键
      if (event.ctrlKey && event.key === 'z' && !event.shiftKey) {
        event.preventDefault()
        handleUndo()
      }
      
      if (event.ctrlKey && event.key === 'z' && event.shiftKey) {
        event.preventDefault()
        handleRedo()
      }
      
      if (event.key === 'Escape') {
        setContextMenuVisible(false)
      }
    }

    const handleClickOutside = (event) => {
      if (contextMenuVisible) {
        setContextMenuVisible(false)
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    document.addEventListener('click', handleClickOutside)
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.removeEventListener('click', handleClickOutside)
    }
  }, [dataSource, currentFileId, contextMenuVisible, historyIndex, history])

  /**
   * 从数据库加载配置数据（当没有指定fileId时使用）
   */
  const loadDataFromDatabase = async () => {
    try {
      // 首先获取文件列表
      const filesResponse = await fetch('http://localhost:3003/api/files')
      if (!filesResponse.ok) {
        throw new Error('获取文件列表失败')
      }
      const files = await filesResponse.json()
      
      if (files.length === 0) {
        // 如果没有文件，创建默认文件
        const createResponse = await fetch('http://localhost:3003/api/files', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ name: '苏州' })
        })
        if (!createResponse.ok) {
          throw new Error('创建默认文件失败')
        }
        const newFile = await createResponse.json()
        setCurrentFileId(newFile.id)
        
        // 加载新创建文件的数据
        await loadFileData(newFile.id)
      } else {
        // 加载第一个文件的数据
        setCurrentFileId(files[0].id)
        await loadFileData(files[0].id)
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      message.error('加载数据失败: ' + error.message)
      // 如果加载失败，使用默认数据
      setDataSource([])
    }
  }

  /**
   * 加载指定文件的配置数据
   */
  const loadFileData = async (fileId) => {
    try {
      const response = await fetch(`http://localhost:3003/api/files/${fileId}/data`)
      if (!response.ok) {
        throw new Error('获取配置数据失败')
      }
      const data = await response.json()
      
      // 转换数据格式，添加key字段
      const formattedData = data.map((item, index) => ({
        key: item.id ? item.id.toString() : (Date.now() + index).toString(),
        sequence: item.sequence_number || index + 1,
        type: item.type ? (typeof item.type === 'string' && isNaN(item.type) ? getTypeValue(item.type) : parseInt(item.type)) : 4,
        startAddr: item.start_addr || '',
        dataType: item.data_type || 1,
        unit: item.unit || '',
        valueType: item.value_type || '',
        variable: item.variable || '',
        description: item.description || ''
      }))
      
      setDataSource(formattedData)
      message.success(`成功加载${formattedData.length}条配置数据`)
    } catch (error) {
      console.error('加载文件数据失败:', error)
      message.error('加载文件数据失败: ' + error.message)
      setDataSource([])
    }
  }

  /**
   * 保存数据到数据库
   */
  const saveDataToDatabase = async (data = dataSource) => {
    // 检查currentFileId是否存在
    if (!currentFileId) {
      console.warn('currentFileId为空，跳过保存')
      return
    }

    try {
      // 转换数据格式
      const saveData = data.map(item => ({
        sequenceNumber: item.sequence,
        type: item.type,
        startAddr: item.startAddr.toString(),
        dataType: item.dataType,
        unit: item.unit || '',
        valueType: item.valueType || '',
        variable: item.variable,
        description: item.description
      }))

      const response = await fetch(`http://localhost:3003/api/files/${currentFileId}/data`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ data: saveData })
      })

      if (!response.ok) {
        throw new Error('保存数据失败')
      }

      message.success('数据保存成功')
    } catch (error) {
      console.error('保存数据失败:', error)
      message.error('保存数据失败: ' + error.message)
    }
  }

  /**
   * 更新单元格数据
   */
  const updateCellData = (key, field, value) => {
    // 保存历史记录
    saveToHistory(`编辑${field}`)
    
    const newData = [...dataSource]
    const index = newData.findIndex((item) => item.key === key)
    if (index > -1) {
      newData[index][field] = value
      setDataSource(newData)
      setHasUnsavedChanges(true)
      onDataChange?.(true)
      // 清除冲突标记，因为数据已变更
      setConflictRows(new Set())
    }
  }

  /**
   * 手动保存功能
   */
  const handleSave = async () => {
    if (!hasUnsavedChanges) {
      message.info('没有需要保存的更改')
      return
    }
    await saveDataToDatabase()
    setHasUnsavedChanges(false)
    onDataChange?.(false)
  }

  /**
   * 可编辑单元格组件
   */
  const EditableCell = ({ record, field, type = 'input', options = [], validation = {}, placeholder = '' }) => {
    const [isEditing, setIsEditing] = useState(false)
    const [value, setValue] = useState(record[field])
    const [originalValue, setOriginalValue] = useState(record[field])
    const [isExpanded, setIsExpanded] = useState(false)
    const [showModal, setShowModal] = useState(false)

    const handleSave = () => {
      // 只有当值真正改变时才保存
      if (value !== originalValue) {
        if (validation.required && (!value || value === '')) {
          message.error(validation.message || '此字段为必填项')
          return
        }
        if (validation.pattern && !validation.pattern.test(value)) {
          message.error(validation.patternMessage || '格式不正确')
          return
        }
        updateCellData(record.key, field, value)
      }
      setIsEditing(false)
    }

    const handleCancel = () => {
      setValue(originalValue)
      setIsEditing(false)
    }

    const handleStartEdit = () => {
      setOriginalValue(record[field])
      setValue(record[field])
      setIsEditing(true)
    }

    if (isEditing) {
      if (type === 'select') {
        return (
          <Select
            value={value}
            onChange={setValue}
            onBlur={handleSave}
            style={{ width: '100%' }}
            autoFocus
          >
            {options.map(option => (
              <Select.Option key={option.value} value={option.value}>
                {option.label}
              </Select.Option>
            ))}
          </Select>
        )
      } else if (type === 'textarea') {
        return (
          <Input.TextArea
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onBlur={handleSave}
            placeholder={placeholder}
            autoFocus
            autoSize={{ minRows: 2, maxRows: 6 }}
            style={{ width: '100%' }}
          />
        )
      } else {
        return (
          <Input
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onBlur={handleSave}
            onPressEnter={handleSave}
            placeholder={placeholder}
            autoFocus
          />
        )
      }
    }

    let displayValue = value
    if (type === 'select' && options.length > 0) {
      const option = options.find(opt => opt.value === value)
      displayValue = option ? option.label : value
    }
    if (field === 'startAddr' && value) {
      displayValue = value.toString().padStart(4, '0')
    }

    // 如果是valueType字段且有内容，根据是否包含###来决定渲染方式
    if (field === 'valueType' && displayValue && displayValue !== '未设置') {
      const hasMarkdownHeaders = /(\n|^)###\s/.test(displayValue)
      
      // 如果不包含###，使用普通文本显示
      if (!hasMarkdownHeaders) {
        return (
          <>
            <div
              style={{
                padding: '4px 8px',
                minHeight: '22px',
                border: '1px solid transparent',
                position: 'relative'
              }}
            >
              <div
                style={{
                  cursor: 'pointer',
                  whiteSpace: 'pre-wrap',
                  lineHeight: '1.4',
                  fontSize: '14px',
                  color: '#262626'
                }}
                onClick={handleStartEdit}
              >
                {displayValue}
              </div>
            </div>
            
            <Modal
               title="文本编辑"
               open={showModal}
               onCancel={() => setShowModal(false)}
               maskClosable={false}
               footer={[
                 <Button key="save" type="primary" onClick={() => {
                   handleSave()
                   setShowModal(false)
                 }}>
                   保存
                 </Button>,
                 <Button key="cancel" onClick={() => setShowModal(false)}>
                   取消
                 </Button>
               ]}
               width={800}
               style={{ top: 20 }}
             >
               <div style={{ height: '60vh' }} onClick={(e) => e.stopPropagation()}>
                 <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>编辑内容：</div>
                 <Input.TextArea
                   value={value}
                   onChange={(e) => setValue(e.target.value)}
                   style={{ height: 'calc(100% - 32px)', resize: 'none' }}
                   placeholder="请输入内容..."
                   onClick={(e) => e.stopPropagation()}
                 />
               </div>
             </Modal>
          </>
        )
      }
      
      // 包含###时使用markdown渲染
      return (
        <>
          <div
            style={{
              padding: '4px 8px',
              minHeight: '22px',
              border: '1px solid transparent',
              position: 'relative'
            }}
          >
            {/* 预览按钮铺满整个单元格 */}
            <div
              style={{
                position: 'absolute',
                left: '0',
                top: '0',
                right: '0',
                bottom: '0',
                background: '#f0f8ff',
                border: '1px solid #1890ff',
                borderRadius: '4px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: '14px',
                cursor: 'pointer',
                color: '#1890ff',
                fontWeight: '500',
                transition: 'all 0.2s ease',
                zIndex: 1
              }}
              onMouseEnter={(e) => {
                e.target.style.background = '#e6f7ff'
                e.target.style.borderColor = '#40a9ff'
              }}
              onMouseLeave={(e) => {
                e.target.style.background = '#f0f8ff'
                e.target.style.borderColor = '#1890ff'
              }}
              onClick={(e) => {
                e.stopPropagation()
                setShowModal(true)
              }}
            >
              预览
            </div>
          </div>
          
          {/* 自定义弹窗 */}
          {showModal && (
            <>
              {/* 遮罩层 */}
              <div
                style={{
                  position: 'fixed',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundColor: 'rgba(0, 0, 0, 0.45)',
                  zIndex: 9998
                }}
                onClick={(e) => e.stopPropagation()}
              />
              {/* 弹窗内容 */}
              <div
                style={{
                  position: 'fixed',
                  top: '50%',
                  left: '50%',
                  transform: 'translate(-50%, -50%)',
                  width: '1200px',
                  maxWidth: '90vw',
                  maxHeight: '90vh',
                  backgroundColor: '#fff',
                  borderRadius: '8px',
                  boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                  zIndex: 9999,
                  display: 'flex',
                  flexDirection: 'column'
                }}
                onClick={(e) => e.stopPropagation()}
              >
                {/* 标题栏 */}
                <div
                  style={{
                    padding: '16px 24px',
                    borderBottom: '1px solid #f0f0f0',
                    fontSize: '16px',
                    fontWeight: 'bold',
                    color: '#262626'
                  }}
                >
                  Markdown 编辑
                </div>
                
                {/* 内容区域 */}
                <div style={{ display: 'flex', height: '70vh', padding: '16px 24px' }}>
                  {/* 左侧编辑区 */}
                  <div style={{ flex: 1, marginRight: '16px' }} onClick={(e) => e.stopPropagation()}>
                    <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>编辑内容：</div>
                    <Input.TextArea
                      value={value}
                      onChange={(e) => setValue(e.target.value)}
                      style={{ height: 'calc(100% - 32px)', resize: 'none' }}
                      placeholder="请输入内容..."
                      onClick={(e) => e.stopPropagation()}
                    />
                  </div>
                  {/* 右侧预览区 */}
                  <div style={{ flex: 1, marginLeft: '16px' }}>
                    <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>预览效果：</div>
                    <div style={{ height: 'calc(100% - 32px)', overflow: 'auto', padding: '16px', backgroundColor: '#fafafa', borderRadius: '6px', border: '1px solid #d9d9d9' }}>
                      <ReactMarkdown
                        remarkPlugins={[remarkGfm]}
                        components={{
                          // 弹窗中的完整样式渲染
                          p: ({ children }) => <p style={{ margin: '12px 0', lineHeight: '1.6', fontSize: '14px' }}>{children}</p>,
                          h1: ({ children }) => <h1 style={{ fontSize: '2em', fontWeight: 'bold', color: '#1890ff', margin: '24px 0 16px 0', borderBottom: '3px solid #1890ff', paddingBottom: '8px' }}>{children}</h1>,
                          h2: ({ children }) => <h2 style={{ fontSize: '1.6em', fontWeight: 'bold', color: '#1890ff', margin: '20px 0 12px 0', borderBottom: '2px solid #d9d9d9', paddingBottom: '6px' }}>{children}</h2>,
                          h3: ({ children }) => <h3 style={{ fontSize: '1.4em', fontWeight: 'bold', color: '#262626', margin: '16px 0 8px 0' }}>{children}</h3>,
                          h4: ({ children }) => <h4 style={{ fontSize: '1.2em', fontWeight: 'bold', color: '#595959', margin: '12px 0 6px 0' }}>{children}</h4>,
                          h5: ({ children }) => <h5 style={{ fontSize: '1.1em', fontWeight: 'bold', color: '#8c8c8c', margin: '10px 0 4px 0' }}>{children}</h5>,
                          h6: ({ children }) => <h6 style={{ fontSize: '1em', fontWeight: 'bold', color: '#bfbfbf', margin: '8px 0 4px 0' }}>{children}</h6>,
                          ul: ({ children }) => <ul style={{ margin: '12px 0', paddingLeft: '24px', listStyleType: 'disc' }}>{children}</ul>,
                          ol: ({ children }) => <ol style={{ margin: '12px 0', paddingLeft: '24px', listStyleType: 'decimal' }}>{children}</ol>,
                          li: ({ children }) => <li style={{ margin: '6px 0', lineHeight: '1.5' }}>{children}</li>,
                          code: ({ children }) => <code style={{ backgroundColor: '#f6f8fa', color: '#d73a49', padding: '4px 8px', borderRadius: '4px', fontSize: '0.9em', border: '1px solid #e1e4e8', fontFamily: 'Consolas, Monaco, "Courier New", monospace' }}>{children}</code>,
                          pre: ({ children }) => <pre style={{ backgroundColor: '#f6f8fa', padding: '16px', borderRadius: '8px', border: '1px solid #e1e4e8', margin: '12px 0', overflow: 'auto', fontSize: '0.9em', fontFamily: 'Consolas, Monaco, "Courier New", monospace', lineHeight: '1.4' }}>{children}</pre>,
                          blockquote: ({ children }) => <blockquote style={{ fontStyle: 'italic', borderLeft: '4px solid #1890ff', paddingLeft: '16px', margin: '12px 0', backgroundColor: '#f0f8ff', padding: '12px 16px', borderRadius: '0 6px 6px 0' }}>{children}</blockquote>,
                          strong: ({ children }) => <strong style={{ color: '#262626', fontWeight: '600' }}>{children}</strong>,
                          em: ({ children }) => <em style={{ color: '#595959', fontStyle: 'italic' }}>{children}</em>,
                          a: ({ children, href }) => <a href={href} style={{ color: '#1890ff', textDecoration: 'underline' }} target="_blank" rel="noopener noreferrer">{children}</a>,
                          hr: () => <hr style={{ border: 'none', borderTop: '2px solid #d9d9d9', margin: '16px 0' }} />,
                          table: ({ children }) => <table style={{ width: '100%', borderCollapse: 'collapse', margin: '12px 0', border: '1px solid #d9d9d9' }}>{children}</table>,
                          thead: ({ children }) => <thead style={{ backgroundColor: '#fafafa' }}>{children}</thead>,
                          tbody: ({ children }) => <tbody>{children}</tbody>,
                          tr: ({ children }) => <tr style={{ borderBottom: '1px solid #e8e8e8' }}>{children}</tr>,
                          th: ({ children }) => <th style={{ padding: '8px 12px', textAlign: 'left', fontWeight: 'bold', borderRight: '1px solid #e8e8e8' }}>{children}</th>,
                          td: ({ children }) => <td style={{ padding: '8px 12px', borderRight: '1px solid #e8e8e8' }}>{children}</td>
                        }}>
                        {value || '暂无内容'}
                      </ReactMarkdown>
                    </div>
                  </div>
                </div>
                
                {/* 底部按钮 */}
                <div
                  style={{
                    padding: '12px 24px',
                    borderTop: '1px solid #f0f0f0',
                    display: 'flex',
                    justifyContent: 'flex-end',
                    gap: '8px'
                  }}
                >
                  <Button onClick={() => setShowModal(false)}>
                    取消
                  </Button>
                  <Button type="primary" onClick={() => {
                    handleSave()
                    setShowModal(false)
                  }}>
                    保存
                  </Button>
                </div>
              </div>
            </>
          )}
        </>
      )
    }

    return (
      <div
        style={{
          cursor: 'pointer',
          padding: '4px 8px',
          minHeight: '22px',
          border: '1px solid transparent',
          whiteSpace: type === 'textarea' ? 'pre-wrap' : 'nowrap',
          wordBreak: type === 'textarea' ? 'break-word' : 'normal'
        }}
        onClick={handleStartEdit}
      >
        {displayValue || '未设置'}
      </div>
    )
  }

  const handleDelete = (key) => {
    // 保存历史记录
    saveToHistory('删除行')
    
    const newData = dataSource.filter((item) => item.key !== key)
    setDataSource(newData)
    setHasUnsavedChanges(true)
    // 清除冲突标记，因为数据已变更
    setConflictRows(new Set())
    message.success('删除成功')
  }

  /**
   * 根据数据类型计算地址偏移量（Modbus RTU协议）
   */
  const getAddressOffset = (dataType) => {
    switch (dataType) {
      case 1: // 16位无符号
      case 2: // 16位有符号
        return 1
      case 3: // 32位无符号
      case 4: // 32位有符号
      case 5: // 32位浮点数
        return 2
      default:
        return 1
    }
  }

  /**
   * 检查地址冲突
   */
  const checkAddressConflicts = () => {
    const conflicts = new Set()
    
    // 按序号排序数据
    const sortedData = [...dataSource].sort((a, b) => a.sequence - b.sequence)
    
    for (let i = 1; i < sortedData.length; i++) {
      const prevRow = sortedData[i - 1]
      const currentRow = sortedData[i]
      
      if (prevRow && currentRow && prevRow.startAddr && currentRow.startAddr) {
        const prevAddress = parseInt(prevRow.startAddr)
        const currentAddress = parseInt(currentRow.startAddr)
        const prevDataType = prevRow.dataType
        
        // 计算前一行应该占用的地址范围
        const expectedNextAddress = prevAddress + getAddressOffset(prevDataType)
        
        // 如果当前行地址小于期望地址，说明有冲突
        if (currentAddress < expectedNextAddress) {
          conflicts.add(currentRow.key)
        }
      }
    }
    
    setConflictRows(conflicts)
    
    if (conflicts.size > 0) {
      message.warning(`发现 ${conflicts.size} 个地址冲突，已标记为红色`)
    } else {
      message.success('未发现地址冲突')
    }
  }

  const handleAdd = () => {
    // 保存历史记录
    saveToHistory('添加行')
    
    const newKey = Date.now().toString()
    const newSequence = dataSource.length > 0 ? Math.max(...dataSource.map(item => item.sequence)) + 1 : 1
    
    // 计算新地址：基于上一行的地址和数据类型
    let newStartAddr = 1
    if (dataSource.length > 0) {
      // 按sequence排序，获取最后一行
      const sortedData = [...dataSource].sort((a, b) => a.sequence - b.sequence)
      const lastRow = sortedData[sortedData.length - 1]
      const offset = getAddressOffset(lastRow.dataType)
      newStartAddr = parseInt(lastRow.startAddr) + offset
    }
    
    const newData = {
      key: newKey,
      sequence: newSequence,
      type: 4,
      startAddr: newStartAddr,
      dataType: 1,
      unit: '',
      valueType: '',
      variable: 'xxx.xxx',
      description: ''
    }
    const updatedData = [...dataSource, newData]
    setDataSource(updatedData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    // 清除冲突标记，因为数据已变更
    setConflictRows(new Set())
  }

  /**
   * 导出JSON功能
   */
  const handleExportJson = () => {
    try {
      // 转换数据格式，移除key字段，只保留需要的字段
      const exportData = dataSource.map(item => ({
        sequence: item.sequence,
        type: item.type,
        startAddr: item.startAddr,
        dataType: item.dataType,
        unit: item.unit,
        valueType: item.valueType,
        variable: item.variable,
        description: item.description
      }))
      
      const jsonString = JSON.stringify(exportData, null, 2)
      const blob = new Blob([jsonString], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'mapping_config.json'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      message.success('JSON文件导出成功')
    } catch (error) {
      message.error('导出失败：' + error.message)
    }
  }

  /**
   * 导出Excel功能
   */
  const handleExportExcel = () => {
    try {
      // 准备导出数据，转换为Excel友好的格式
      const exportData = dataSource.map(item => ({
        '序号': item.sequence,
        '描述': item.description || '',
        '类型': getTypeString(item.type),
        '开始地址': item.startAddr,
        '数据类型': getDataTypeString(item.dataType),
        '单位': item.unit || '',
        '值类型': item.valueType || '',
        '绑定变量': item.variable || ''
      }))
      
      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '配置数据')
      
      // 设置列宽
      const colWidths = [
        { wch: 8 },  // 序号
        { wch: 25 }, // 描述
        { wch: 15 }, // 类型
        { wch: 12 }, // 开始地址
        { wch: 15 }, // 数据类型
        { wch: 10 }, // 单位
        { wch: 20 }, // 值类型
        { wch: 20 }  // 绑定变量
      ]
      ws['!cols'] = colWidths
      
      // 导出文件
      XLSX.writeFile(wb, 'mapping_config.xlsx')
      message.success('Excel文件导出成功')
    } catch (error) {
      message.error('导出失败：' + error.message)
    }
  }

  /**
   * 导入JSON功能
   */
  const handleImportJson = (file) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const jsonData = JSON.parse(e.target.result)
        if (Array.isArray(jsonData)) {
          // 为每个数据项添加key字段
          const importedData = jsonData.map((item, index) => ({
            ...item,
            key: Date.now().toString() + index,
            sequence: item.sequence || index + 1
          }))
          setDataSource(importedData)
          setHasUnsavedChanges(true)
          onDataChange?.(true)
          message.success(`成功导入${importedData.length}条配置数据`)
        } else {
          message.error('JSON格式错误：数据应该是数组格式')
        }
      } catch (error) {
        message.error('JSON文件解析失败：' + error.message)
      }
    }
    reader.readAsText(file)
    return false // 阻止默认上传行为
  }

  /**
   * 批量删除功能
   */
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的行')
      return
    }
    // 保存历史记录
    saveToHistory(`批量删除${selectedRowKeys.length}行`)
    
    const newData = dataSource.filter((item) => !selectedRowKeys.includes(item.key))
    setDataSource(newData)
    setSelectedRowKeys([])
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    // 清除冲突标记，因为数据已变更
    setConflictRows(new Set())
    message.success(`成功删除${selectedRowKeys.length}行数据`)
  }



  /**
   * 处理列宽调整
   */
  const handleResize = (index) => (e, { size }) => {
    const newColumns = [...columns]
    newColumns[index] = {
      ...newColumns[index],
      width: size.width,
    }
    setColumns(newColumns)
  }

  /**
   * 筛选数据源
   */
  const filteredDataSource = dataSource.filter(item => {
    if (!searchKeyword) return true
    
    const keyword = searchKeyword.toLowerCase()
    const startAddr = item.startAddr?.toString().toLowerCase() || ''
    const variable = item.variable?.toLowerCase() || ''
    const description = item.description?.toLowerCase() || ''
    const unit = item.unit?.toLowerCase() || ''
    const valueType = item.valueType?.toLowerCase() || ''
    
    return startAddr.includes(keyword) || 
           variable.includes(keyword) || 
           description.includes(keyword) ||
           unit.includes(keyword) ||
           valueType.includes(keyword)
  })

  /**
   * 处理右键菜单
   */
  const handleContextMenu = (e, record, index) => {
    e.preventDefault()
    setContextMenuPosition({ x: e.clientX, y: e.clientY })
    setContextMenuRowIndex(index)
    setContextMenuVisible(true)
  }

  /**
   * 关闭右键菜单
   */
  const handleContextMenuClose = () => {
    setContextMenuVisible(false)
  }

  /**
   * 开始框选
   */
  const handleMouseDown = (e) => {
    // 只在表格区域且不是右键时启用框选
    if (e.button !== 0 || e.target.closest('.ant-table-cell')) return
    
    const tableContainer = e.currentTarget
    const rect = tableContainer.getBoundingClientRect()
    const startX = e.clientX - rect.left
    const startY = e.clientY - rect.top
    
    setIsSelecting(true)
    setSelectionStart({ x: startX, y: startY })
    setSelectionEnd({ x: startX, y: startY })
    setSelectionBox({
      display: 'block',
      left: startX,
      top: startY,
      width: 0,
      height: 0
    })
    
    e.preventDefault()
  }

  /**
   * 框选过程中
   */
  const handleMouseMove = (e) => {
    if (!isSelecting) return
    
    const tableContainer = e.currentTarget
    const rect = tableContainer.getBoundingClientRect()
    const currentX = e.clientX - rect.left
    const currentY = e.clientY - rect.top
    
    setSelectionEnd({ x: currentX, y: currentY })
    
    const left = Math.min(selectionStart.x, currentX)
    const top = Math.min(selectionStart.y, currentY)
    const width = Math.abs(currentX - selectionStart.x)
    const height = Math.abs(currentY - selectionStart.y)
    
    setSelectionBox({
      display: 'block',
      left,
      top,
      width,
      height
    })
    
    // 计算框选范围内的行
    const tableBody = tableContainer.querySelector('.ant-table-tbody')
    if (tableBody) {
      const rows = tableBody.querySelectorAll('tr')
      const selectedKeys = []
      
      rows.forEach((row, index) => {
        const rowRect = row.getBoundingClientRect()
        const containerRect = tableContainer.getBoundingClientRect()
        const rowTop = rowRect.top - containerRect.top
        const rowBottom = rowRect.bottom - containerRect.top
        
        // 检查行是否与选择框相交
        if (rowBottom >= top && rowTop <= top + height) {
          const rowData = filteredDataSource[index]
          if (rowData) {
            selectedKeys.push(rowData.key)
          }
        }
      })
      
      setSelectedRowKeys(selectedKeys)
    }
  }

  /**
   * 结束框选
   */
  const handleMouseUp = () => {
    if (isSelecting) {
      setIsSelecting(false)
      setSelectionBox({ display: 'none', left: 0, top: 0, width: 0, height: 0 })
    }
  }

  /**
   * 保存历史记录
   */
  const saveToHistory = (operation) => {
    if (isUndoRedoOperation) return
    
    const historyItem = {
      data: JSON.parse(JSON.stringify(dataSource)), // 深拷贝当前数据
      selectedRowKeys: [...selectedRowKeys],
      operation,
      timestamp: Date.now()
    }
    
    // 如果当前不在历史记录的末尾，删除后面的记录
    const newHistory = history.slice(0, historyIndex + 1)
    newHistory.push(historyItem)
    
    // 限制历史记录数量（最多50条）
    if (newHistory.length > 50) {
      newHistory.shift()
    } else {
      setHistoryIndex(historyIndex + 1)
    }
    
    setHistory(newHistory)
  }

  /**
   * 撤销操作
   */
  const handleUndo = () => {
    if (historyIndex > 0) {
      const historyItem = history[historyIndex - 1]
      setIsUndoRedoOperation(true)
      
      setDataSource(JSON.parse(JSON.stringify(historyItem.data)))
      setSelectedRowKeys([...historyItem.selectedRowKeys])
      setHistoryIndex(historyIndex - 1)
      setHasUnsavedChanges(true)
      onDataChange?.(true)
      
      setTimeout(() => setIsUndoRedoOperation(false), 100)
      message.success(`撤销操作：${history[historyIndex].operation}`)
    }
  }

  /**
   * 重做操作
   */
  const handleRedo = () => {
    if (historyIndex < history.length - 1) {
      const nextIndex = historyIndex + 1
      const historyItem = history[nextIndex]
      setIsUndoRedoOperation(true)
      
      setDataSource(JSON.parse(JSON.stringify(historyItem.data)))
      setSelectedRowKeys([...historyItem.selectedRowKeys])
      setHistoryIndex(nextIndex)
      setHasUnsavedChanges(true)
      onDataChange?.(true)
      
      setTimeout(() => setIsUndoRedoOperation(false), 100)
      message.success(`重做操作：${historyItem.operation}`)
    }
  }

  /**
   * 批量编辑单位
   */
  const handleBatchEditUnit = (newUnit) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要编辑的行')
      return
    }
    // 保存历史记录
      saveToHistory(`批量编辑单位`)
    
    const newData = dataSource.map(item => {
      if (selectedRowKeys.includes(item.key)) {
        return { ...item, unit: newUnit }
      }
      return item
    })
    setDataSource(newData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    message.success(`成功批量修改${selectedRowKeys.length}行的单位`)
  }

  /**
   * 批量编辑寄存器类型
   */
  const handleBatchEditType = (newType) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要编辑的行')
      return
    }
    // 保存历史记录
      saveToHistory(`批量编辑寄存器类型`)
    
    const newData = dataSource.map(item => {
      if (selectedRowKeys.includes(item.key)) {
        return { ...item, type: newType }
      }
      return item
    })
    setDataSource(newData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    message.success(`成功批量修改${selectedRowKeys.length}行的寄存器类型`)
  }

  /**
   * 批量编辑数据类型
   */
  const handleBatchEditDataType = (newDataType) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要编辑的行')
      return
    }
    // 保存历史记录
      saveToHistory(`批量编辑数据类型`)
    
    const newData = dataSource.map(item => {
      if (selectedRowKeys.includes(item.key)) {
        return { ...item, dataType: newDataType }
      }
      return item
    })
    setDataSource(newData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    message.success(`成功批量修改${selectedRowKeys.length}行的数据类型`)
  }

  /**
   * 批量编辑值类型
   */
  const handleBatchEditValueType = (newValueType) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要编辑的行')
      return
    }
    // 保存历史记录
      saveToHistory(`批量编辑值类型`)
    
    const newData = dataSource.map(item => {
      if (selectedRowKeys.includes(item.key)) {
        return { ...item, valueType: newValueType }
      }
      return item
    })
    setDataSource(newData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    message.success(`成功批量修改${selectedRowKeys.length}行的值类型`)
  }

  /**
   * 右键菜单项配置
   */
  const contextMenuItems = [
    // 撤销重做选项（始终显示）
    {
      key: 'undo',
      label: `撤销 (Ctrl+Z)`,
      onClick: () => {
        handleUndo()
        handleContextMenuClose()
      },
      disabled: historyIndex <= 0
    },
    {
      key: 'redo',
      label: `重做 (Ctrl+Shift+Z)`,
      onClick: () => {
        handleRedo()
        handleContextMenuClose()
      },
      disabled: historyIndex >= history.length - 1 || history.length <= 1
    },
    {
      type: 'divider'
    },
    // 根据选择状态显示不同选项
    ...(selectedRowKeys.length > 1 ? [
      // 多选模式下的批量编辑菜单
      {
        key: 'batch-edit-unit',
        label: '批量编辑单位',
        children: [
          { key: 'unit-empty', label: '清空单位', onClick: () => { handleBatchEditUnit(''); handleContextMenuClose() } },
          { key: 'unit-kg', label: '设为 kg', onClick: () => { handleBatchEditUnit('kg'); handleContextMenuClose() } },
          { key: 'unit-m', label: '设为 m', onClick: () => { handleBatchEditUnit('m'); handleContextMenuClose() } },
          { key: 'unit-s', label: '设为 s', onClick: () => { handleBatchEditUnit('s'); handleContextMenuClose() } },
          { key: 'unit-a', label: '设为 A', onClick: () => { handleBatchEditUnit('A'); handleContextMenuClose() } },
          { key: 'unit-v', label: '设为 V', onClick: () => { handleBatchEditUnit('V'); handleContextMenuClose() } },
          { key: 'unit-w', label: '设为 W', onClick: () => { handleBatchEditUnit('W'); handleContextMenuClose() } },
          { key: 'unit-celsius', label: '设为 ℃', onClick: () => { handleBatchEditUnit('℃'); handleContextMenuClose() } },
          { key: 'unit-percent', label: '设为 %', onClick: () => { handleBatchEditUnit('%'); handleContextMenuClose() } }
        ]
      },
      {
        key: 'batch-edit-type',
        label: '批量编辑寄存器类型',
        children: [
          { key: 'type-1', label: '输入线电器', onClick: () => { handleBatchEditType(1); handleContextMenuClose() } },
          { key: 'type-2', label: '输出线电器', onClick: () => { handleBatchEditType(2); handleContextMenuClose() } },
          { key: 'type-3', label: '输入寄存器', onClick: () => { handleBatchEditType(3); handleContextMenuClose() } },
          { key: 'type-4', label: '输出寄存器', onClick: () => { handleBatchEditType(4); handleContextMenuClose() } }
        ]
      },
      {
        key: 'batch-edit-datatype',
        label: '批量编辑数据类型',
        children: [
          { key: 'datatype-1', label: '16位无符号', onClick: () => { handleBatchEditDataType(1); handleContextMenuClose() } },
          { key: 'datatype-2', label: '16位有符号', onClick: () => { handleBatchEditDataType(2); handleContextMenuClose() } },
          { key: 'datatype-3', label: '32位无符号', onClick: () => { handleBatchEditDataType(3); handleContextMenuClose() } },
          { key: 'datatype-4', label: '32位有符号', onClick: () => { handleBatchEditDataType(4); handleContextMenuClose() } },
          { key: 'datatype-5', label: '32位浮点型', onClick: () => { handleBatchEditDataType(5); handleContextMenuClose() } },
          { key: 'datatype-6', label: '16位4位BCD', onClick: () => { handleBatchEditDataType(6); handleContextMenuClose() } },
          { key: 'datatype-7', label: '32位8位BCD', onClick: () => { handleBatchEditDataType(7); handleContextMenuClose() } }
        ]
      },
      {
        key: 'batch-edit-valuetype',
        label: '批量编辑值类型',
        children: [
          { key: 'valuetype-empty', label: '清空值类型', onClick: () => { handleBatchEditValueType(''); handleContextMenuClose() } },
          { key: 'valuetype-readonly', label: '只读', onClick: () => { handleBatchEditValueType('只读'); handleContextMenuClose() } },
          { key: 'valuetype-readwrite', label: '读写', onClick: () => { handleBatchEditValueType('读写'); handleContextMenuClose() } },
          { key: 'valuetype-writeonly', label: '只写', onClick: () => { handleBatchEditValueType('只写'); handleContextMenuClose() } }
        ]
      },
      {
         type: 'divider'
       },
       {
         key: 'clear-selection',
         label: '取消多选',
         onClick: () => {
           setSelectedRowKeys([])
           handleContextMenuClose()
           message.info('已取消选择')
         }
       },
       {
         key: 'batch-delete',
         label: `删除选中的${selectedRowKeys.length}行`,
         danger: true,
         onClick: () => {
           handleBatchDelete()
           handleContextMenuClose()
         }
       }
    ] : [
      // 单选或无选择模式下的原有菜单
      {
        key: 'insert-before',
        label: '在此行前插入',
        onClick: () => {
          handleInsertRow(contextMenuRowIndex, 'before')
          handleContextMenuClose()
        }
      },
      {
        key: 'insert-after',
        label: '在此行后插入',
        onClick: () => {
          handleInsertRow(contextMenuRowIndex, 'after')
          handleContextMenuClose()
        }
      },
      {
        type: 'divider'
      },
      {
        key: 'delete',
        label: '删除此行',
        danger: true,
        onClick: () => {
          const record = filteredDataSource[contextMenuRowIndex]
          if (record) {
            handleDelete(record.key)
          }
          handleContextMenuClose()
        }
      }
    ])
  ]

  /**
   * 在指定位置插入新行
   */
  const handleInsertRow = (targetIndex, position = 'after') => {
    const newKey = Date.now().toString()
    const insertIndex = position === 'before' ? targetIndex : targetIndex + 1
    
    // 重新计算序号和地址
    const newData = [...dataSource]
    
    // 计算新行的地址
    let newStartAddr = 1
    if (newData.length > 0) {
      if (position === 'before' && targetIndex > 0) {
        // 插入到前面，基于前一行计算
        const prevRow = newData[targetIndex - 1]
        const offset = getAddressOffset(prevRow.dataType)
        newStartAddr = parseInt(prevRow.startAddr) + offset
      } else if (position === 'after') {
        // 插入到后面，基于当前行计算
        const currentRow = newData[targetIndex]
        const offset = getAddressOffset(currentRow.dataType)
        newStartAddr = parseInt(currentRow.startAddr) + offset
      } else {
        // 插入到最前面
        newStartAddr = 1
      }
    }
    
    const newRow = {
      key: newKey,
      sequence: insertIndex + 1,
      type: 4,
      startAddr: newStartAddr,
      dataType: 1,
      unit: '',
      valueType: '',
      variable: 'xxx.xxx',
      description: ''
    }
    
    // 插入新行
    newData.splice(insertIndex, 0, newRow)
    
    // 重新计算所有行的序号
    newData.forEach((item, index) => {
      item.sequence = index + 1
    })
    
    setDataSource(newData)
    setHasUnsavedChanges(true)
    onDataChange?.(true)
    setConflictRows(new Set())
    message.success(`已在第${insertIndex + 1}行${position === 'before' ? '前' : '后'}插入新行`)
  }

  // 创建带有render函数的可调整列配置
  const resizableColumns = columns.map((col, index) => {
    const columnConfig = {
      ...col,
      onHeaderCell: (column) => ({
        width: column.width,
        onResize: handleResize(index),
      }),
    }

    // 根据列的key添加对应的render函数
    switch (col.key) {
      case 'sequence':
        columnConfig.render = (text, record, index) => (
          <div style={{ textAlign: 'center' }}>
            {index + 1}
          </div>
        )
        break
      case 'type':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="type"
            type="select"
            options={[
              { value: 1, label: '输入线电器' },
              { value: 2, label: '输出线电器' },
              { value: 3, label: '输入寄存器' },
              { value: 4, label: '输出寄存器' }
            ]}
            validation={{
              required: true,
              message: '请选择类型'
            }}
          />
        )
        break
      case 'startAddr':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="startAddr"
            type="input"
            placeholder="请输入开始地址"
            validation={{
              required: true,
              message: '请输入开始地址',
              pattern: /^[1-9]\d{0,3}$/,
              patternMessage: '开始地址必须是1-9999之间的数字'
            }}
          />
        )
        break
      case 'dataType':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="dataType"
            type="select"
            options={[
              { value: 1, label: '16位无符号' },
              { value: 2, label: '16位有符号' },
              { value: 3, label: '32位无符号' },
              { value: 4, label: '32位有符号' },
              { value: 5, label: '32位浮点型' },
              { value: 6, label: '16位4位BCD' },
              { value: 7, label: '32位8位BCD' }
            ]}
            validation={{
              required: true,
              message: '请选择数据类型'
            }}
          />
        )
        break
      case 'unit':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="unit"
            type="input"
            placeholder="请输入单位"
          />
        )
        break
      case 'valueType':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="valueType"
            type="textarea"
            placeholder="请输入值类型（支持多行）"
          />
        )
        break
      case 'variable':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="variable"
            type="input"
            placeholder="请输入绑定变量"
            validation={{
              required: true,
              message: '请输入绑定变量',
              pattern: /^[A-Za-z0-9]+\.[A-Za-z0-9]+$/,
              patternMessage: '绑定变量格式必须是XXXX.xxxx'
            }}
          />
        )
        break
      case 'description':
        columnConfig.render = (_, record) => (
          <EditableCell
            record={record}
            field="description"
            type="input"
            placeholder="请输入描述"
          />
        )
        break
      default:
        break
    }

    return columnConfig
  })

  // 选择框配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys) => {
      setSelectedRowKeys(newSelectedRowKeys)
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      if (selected) {
        // 只选择当前筛选显示的行
        setSelectedRowKeys(filteredDataSource.map(item => item.key))
      } else {
        setSelectedRowKeys([])
      }
    },
  }

  return (
    <div 
      className="table-container" 
      style={{ margin: 0, padding: 0, position: 'relative', userSelect: 'none' }}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseUp}
    >
      <Card style={{ margin: 0 }}>
        <div style={{ marginBottom: 16 }}>
          <Input.Search
            placeholder="搜索地址、变量名或描述"
            allowClear
            style={{ width: 300, marginBottom: 16 }}
            value={searchKeyword}
            onSearch={(value) => {
              setSearchKeyword(value)
            }}
            onChange={(e) => {
              setSearchKeyword(e.target.value)
            }}
          />
        </div>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" onClick={handleAdd}>
              添加行
            </Button>
            <Popconfirm
              title="确定要删除选中的行吗？"
              onConfirm={handleBatchDelete}
              okText="确定"
              cancelText="取消"
            >
              <Button danger disabled={selectedRowKeys.length === 0}>
                删除选中行 ({selectedRowKeys.length})
              </Button>
            </Popconfirm>
            <Button 
              type={hasUnsavedChanges ? "primary" : "default"}
              onClick={handleSave}
              disabled={!hasUnsavedChanges}
            >
              保存 (Ctrl+S) {hasUnsavedChanges && '*'}
            </Button>
            <Button 
              onClick={checkAddressConflicts}
            >
              检查地址冲突
            </Button>
            <Upload
              accept=".json"
              beforeUpload={handleImportJson}
              showUploadList={false}
            >
              <Button icon={<UploadOutlined />}>
                导入JSON
              </Button>
            </Upload>
            <Button 
              icon={<DownloadOutlined />} 
              onClick={handleExportJson}
              disabled={dataSource.length === 0}
            >
              导出JSON
            </Button>
            <Button 
              icon={<DownloadOutlined />} 
              onClick={handleExportExcel}
              disabled={dataSource.length === 0}
            >
              导出Excel
            </Button>
          </Space>
        </div>
        <Table
          bordered
          dataSource={filteredDataSource}
          columns={resizableColumns}
          rowKey="key"
          pagination={false}
          scroll={{ x: 800 }}
          rowSelection={rowSelection}
          rowClassName={(record) => conflictRows.has(record.key) ? 'conflict-row' : ''}
          components={{
            header: {
              cell: ResizableTitle,
            },
          }}
          onRow={(record, index) => ({
            onContextMenu: (e) => handleContextMenu(e, record, index)
          })}
        />
        
        {/* 右键菜单 */}
        <Dropdown
          open={contextMenuVisible}
          onOpenChange={setContextMenuVisible}
          menu={{ items: contextMenuItems }}
          trigger={[]}
        >
          <div
            style={{
              position: 'fixed',
              left: contextMenuPosition.x,
              top: contextMenuPosition.y,
              width: 1,
              height: 1,
              pointerEvents: 'none'
            }}
          />
        </Dropdown>
        
        {/* 框选选择框 */}
        <div
          style={{
            position: 'absolute',
            border: '1px dashed #1890ff',
            backgroundColor: 'rgba(24, 144, 255, 0.1)',
            pointerEvents: 'none',
            zIndex: 1000,
            ...selectionBox
          }}
        />
      </Card>
    </div>
  )
}

export default EditableTable
